import { memo, useRef } from "react";
import { addEvent, removeEvent, throttle } from "@/utils";

const RowItem = memo(({ index, addRowWidth, isActive, width }) => {
  const resizeStartPos = useRef();
  function handleResize(e) {
    resizeStartPos.current = e.clientX;
    const _handleMove = throttle(handleMove, 20);
    addEvent(document, "mousemove", _handleMove);
    addEvent(document, "mouseup", handleUp);

    function handleMove(e) {
      const distance = e.clientX - resizeStartPos.current;
      addRowWidth(width + distance);
    }

    function handleUp() {
      removeEvent(document, "mousemove", _handleMove);
      removeEvent(document, "mouseup", handleUp);
    }
  }

  return (
    <div
      className={`cr row-item ${isActive ? "active" : ""}`}
      style={{ width: `${width}px` }}
      data-row={index}
    >
      {index}
      <div
        className="row-resize"
        data-row={index}
        onMouseDown={(e) => handleResize(e)}
      ></div>
    </div>
  );
});

export default RowItem;
